package com.tinem.platform.service.data.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.util.HttpMethod;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.pojo.vo.data.TranslateInfo;
import com.tinem.platform.module.pojo.vo.data.TranslateRes;
import com.tinem.platform.module.pojo.vo.data.TranslateVO;
import com.tinem.platform.module.pojo.vo.error.UserException;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.service.data.service.TranslateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: platform
 * @description: ${description}
 * @author: eden#can
 * @Slogan: 没有所谓失败，除非你不再尝试
 * @date: 2021-11-10 16:41
 **/
@Slf4j
@Api(value = "trans")
@RestController
@RequestMapping("/trans")
public class TranslateApi {

    @Resource
    TranslateService translateService;


    @PostMapping("/language/list.api")
    @ResponseBody
    @ApiOperation(value = "语言列表", httpMethod = HttpMethod.POST, notes = "暂无")
    public Object languageList(HttpServletRequest request, HttpServletResponse response) {

        String lang = request.getHeader(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_LANG);

        return translateService.languageList(lang);
    }



    @PostMapping("/translate.api")
    @ApiOperation(value = "获取翻译结果", httpMethod = "POST", notes = "暂无")
    @ResponseBody
    public TranslateRes translate(@Validated @RequestBody TranslateVO req) {
        log.info("translate.api req:{}", JSONUtil.toJsonStr(req));
        TranslateRes translateRes = new TranslateRes();

        // 翻译通过的数据
        ArrayList<TranslateInfo> list = new ArrayList<>();

        // 缓存不存在的数据
        ArrayList<String> notInCachelist = new ArrayList<>();

        // 查询缓存中是否有翻译过的数据
        if("enable".equals(req.getCache())){
            req.getTransMsgList().stream().forEach(transMsg -> {
                TranslateInfo translateInfo = new TranslateInfo();
                String shaStr = StrUtil.format("{}{}{}", transMsg.trim(),
                                req.getFromLan(), req.getToLan());
                String sha256 = SecureUtil.sha256(shaStr);
                String tarMsg = translateService.getTranslateResult(sha256);
                if(StrUtil.isNotBlank(tarMsg)){
                    translateInfo.setSrc(transMsg);
                    translateInfo.setDst(tarMsg);
                    list.add(translateInfo);
                } else {
                    notInCachelist.add(transMsg);
                }
            });
        }

        if(notInCachelist.size() > 0){
            if(StrUtil.equals(req.getType(),"baidu")){
                List<TranslateInfo> translateList = translateService.getTranslateByBaiduResult(
                        notInCachelist,req);
                if(translateList != null){
                    list.addAll(translateList);
                }
            } else {
                log.error("translate type（{}） is error",req.getType());
                throw new UserException(MessageCode.ERROR_COMMONS_PARAMS,"type");
            }
        }

        translateRes.setTransMsgList(list);
        translateRes.setFromLan(req.getFromLan());
        translateRes.setToLan(req.getToLan());
        translateRes.setType(req.getType());
        return translateRes;
    }

}
